package com.self.test.gaobingfa;

import java.util.concurrent.TimeUnit;
/**
 * 对业务写方法加锁
 * 对业务读方法不加锁
 * 容易产生脏读问题（dirtyRead）
 * 有可能读到在写过程中还没有完成的数据
 * **/
public class SynchronizedTest2 {

	String name;
	double balance;
	
	public synchronized void set(String name, double balance) {
		this.name = name;
		
		/*try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}*/
		
		
		
		this.balance = balance;
	}
	
	public synchronized void update(String name, double balance) {
		this.name = name;
		this.balance += balance;
	}
	
	public synchronized  double getBalance(String name) {
		return this.balance;
	}
	
	public static void main(String[] args) {
		final SynchronizedTest2 t = new SynchronizedTest2();
		
		new Thread(new Runnable() {
			@Override
			public void run() {
				t.set("zhangsan", 100.0);
			}
		}).start();
		
		new Thread(new Runnable() {
			@Override
			public void run() {
				System.out.println(t.getBalance("zhangsan"));
			}
		}).start();
		
		new Thread(new Runnable() {
			@Override
			public void run() {
				t.update("zhangsan", 150.0);
			}
		}).start();
		
		new Thread(new Runnable() {
			@Override
			public void run() {
				System.out.println(t.getBalance("zhangsan"));
			}
		}).start();
		test();
		/*try {
			TimeUnit.SECONDS.sleep(1);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(t.getBalance("zhangsan"));
		
		try {
			TimeUnit.SECONDS.sleep(2);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(t.getBalance("zhangsan"));
		
		new Thread(new Runnable() {
			@Override
			public void run() {
				t.update("zhangsan", 150.0);
			}
		}).start();
		
		try {
			TimeUnit.SECONDS.sleep(3);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(t.getBalance("zhangsan"));*/
		
	}
	
	public static void test() {
		final SynchronizedTest2 t = new SynchronizedTest2();
		
		new Thread(new Runnable() {
			@Override
			public void run() {
				t.set("zhangsan", 100.0);
			}
		}).start();
		
		new Thread(new Runnable() {
			@Override
			public void run() {
				System.out.println(t.getBalance("zhangsan"));
			}
		}).start();
		
		new Thread(new Runnable() {
			@Override
			public void run() {
				t.update("zhangsan", 150.0);
			}
		}).start();
		
		new Thread(new Runnable() {
			@Override
			public void run() {
				System.out.println(t.getBalance("zhangsan"));
			}
		}).start();
	}


}
